package com.wei.web.demo.user.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@RestController
@Slf4j
public class WebSocketController extends TextWebSocketHandler {


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("WebSocket服务端连接: " + session.getAttributes().get("token") + "===>");

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("WebSocket服务端关闭: 关闭连接状态: " + status);

        //socket关闭处理业务逻辑；
        closeSession(getToken(session));
    }

    @Override
    public void handleMessage(WebSocketSession wsSession, WebSocketMessage<?> message) throws Exception {
        String textMsg = message.getPayload().toString();
        log.info("WebSocket服务端接受:接受来自客户端发送的信息. text: " + textMsg);
        TextMessage textMessage = new TextMessage("echo back: " + textMsg);
        wsSession.sendMessage(textMessage);
        log.info("WebSocket服务端接受:接受来自客户端发送的信息 send back. text: " + textMsg);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("WebSocket服务端异常:连接异常信息: " + exception.getMessage());
        log.info("token : " + getToken(session) + " => " + exception.getMessage());
        closeSession(getToken(session));
    }

    private static String getToken(WebSocketSession session) {
        return String.valueOf(session.getAttributes().get("token"));
    }


    private static void closeSession(String token) {
        log.info("关闭通信后 处理业务 token: " + token);
    }


}
